import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;

import static java.util.Arrays.asList;


/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 10/10/13
 * Time: 1:26 PM
 * To change this template use File | Settings | File Templates.
 */
public class MainMenu {
    private final BufferedReader bufferedReader;
    HashMap<Integer, String> menuOptions;
    ArrayList<Player> playersList;

    private PrintStream printStream;


    public MainMenu(PrintStream printStream, BufferedReader bufferedReader) {

        createMenu();
        ArrayList<Coach> coaches1 = new ArrayList<Coach>(asList(new Coach("Micheal Pay", "Head Coach"), new Coach("Charlie", "Assistant Coach")));
        ArrayList<Coach> coaches2 = new ArrayList<Coach>();
        coaches2.add(new Coach("Jimmy Jones", "Head Coach"));
        Team team1 = new Team("Team 1", coaches1);
        Team team2 = new Team("Team 2", coaches2);
        playersList = new ArrayList<Player>(asList(new Player("Alex", team1, 0, 6)
                , new Player("Bill", team2, 1, 18)));

        this.printStream = printStream;
        this.bufferedReader = bufferedReader;
    }

    public void createMenu() {
        menuOptions = new HashMap<Integer, String>();
        menuOptions.put(1, "List Players");
        menuOptions.put(2, "Find A Player");
    }

    public void printListOfAllPlayers() {
        String output = "";

        for (Player player: playersList) {
            output += player.name+ " "
                    + player.team.teamName+ " "
                    + player.team.getCoaches() +" "
                    + player.number+ " "
                    + player.age+"\n";

        }
        printStream.print(output);
    }

    public void pickMenuOption() throws IOException {
        printMenuOptions();
        int input = Integer.parseInt(readUserInput());
        invokeOptionSelected(input);

    }

    public void invokeOptionSelected(int input) throws IOException {
        switch(input){
            case 1: printListOfAllPlayers();
                break;
            case 2: printStream.println("Type Player Name");
                findPlayer(readUserInput());
            default:
                printStream.println("Select a valid option");
        }
    }

    private void findPlayer(String playerName) {
        String found= "Player not found";
        for (Player player : playersList) {
            if(player.name.equals(playerName)){
               found ="Player Found";
            }
        }

        printStream.println(found);
    }

    protected void printMenuOptions() {
        String output = "Select and option\n";
        for (Integer id : menuOptions.keySet()) {
            output += id +" " +menuOptions.get(id)+ "\n";
        }
        printStream.print(output);
    }


    public String readUserInput() throws IOException {
        return bufferedReader.readLine();
    }
}
